var muniClass = {
	parent: "parentId",
	pattern: "4H",
	win: null,
	form: null,
	grid: null,
	statusGrid: null,
	layout: null,
	widgetWin: function(){
		var me = this,
            windows = new dhtmlXWindows();

		me.win = windows.createWindow('window_1', 0, 0, 640, 425);
		me.win.setText('Municipios');
        me.win.setIcon('icon_09.png');
		me.win.button('park').hide();
		me.win.button('minmax1').hide();
		me.win.denyResize();
		me.win.setModal(1);
		me.win.centerOnScreen();
		
		widgetBar(me.win,1);
		me.layout = me.win.attachLayout('2U');
	},	
	widgetGrid: function(){
		var me = this,
            cell = this.layout.cells('a');

		cell.setWidth('300');
		cell.hideHeader();
		cell.fixSize(true, true);

		me.statusGrid = cell.attachStatusBar();
		
		me.grid = cell.attachGrid();		
		me.grid.setImagePath(mainPath+'dhtmlx/imgs/');
		me.grid.setHeader("Id,Código,Detalle,Departamento,DptoCodigo");
		me.grid.setColTypes("ro,ro,ro,ro,ro");		
		me.grid.setColAlign("right,left,left,left,left");
		me.grid.setInitWidths("30,50,198,80,80");		
		me.grid.setColumnColor("#E5E5E5");
        me.grid.setColumnHidden(3,true);
        me.grid.setColumnHidden(4,true);
		me.grid.init();

        me.onEventLoadData();
	},
    onEventLoadData: function(){
        var me = this;

        me.grid.load(mainPath+"index.php/municipio/grid_data", function(){
            me.grid.groupBy(3);
            me.grid.collapseAllGroups();
            me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
        },"json");
    },
	widgetForm: function(){
		var me =  this,
            panel = me.layout.cells('b'),
            str;

        panel.setWidth('250');
		panel.hideHeader();
		str = [
			{ type:"settings" , labelWidth:84, inputWidth:250, position:"absolute"  },
			{ type:"select" , name:"mun_dpto", label:"Departamento:", validate: "NotEmpty", connector: mainPath+"index.php/dpto/combo_data", labelAlign:"right", inputWidth:190, labelLeft:6, labelTop:25, inputLeft:93, inputTop:25  },
			{ type:"input" , name:"mun_codigo", label:"Codigo:", labelAlign:"right", validate: "NotEmpty", inputWidth:80, labelLeft:6, labelTop:50, inputLeft:93, inputTop:50  },
			{ type:"input" , name:"mun_detalle", label:"Detalle:", labelAlign:"right", validate: "NotEmpty", inputWidth:217, labelLeft:6, labelTop:75, inputLeft:93, inputTop:75  },
			{ type:"button" , name:"edit_btn", label:"Button", value:"Modificar", width:"75", inputWidth:75, inputLeft:155, inputTop:100  },
			{ type:"button" , name:"save_btn", label:"Button", value:"Guardar", width:"75", inputWidth:75, inputLeft:235, inputTop:100  }
		];

		me.form = panel.attachForm(str);
		me.form.lock();
	},
    onEventForm: function(){
        var me = this;

        me.form.attachEvent("onButtonClick", function(name) {
            switch(name){
                case 'save_btn':
                    me.onClickButtonSaveData();
                break;
                case 'edit_btn':
                    me.onClickButtonEditData();
                break;
            }
        });
    },
    onClickButtonSaveData: function(){
        var me = this,
            id,
            resData,
            auxFind,
            valCell,
            data = me.form.getFormData();

        if(me.form.validate()){
            auxFind = me.grid.findCell(data.mun_codigo,1);
            valCell = (auxFind != '')?me.grid.cells(auxFind[0][0],auxFind[0][1]).getValue():null;
            if(valCell != data.mun_codigo){
                me.form.send(mainPath+'index.php/municipio/save_data', function(loader, response) {
                    resData = response.split('-');
                    if(resData[0] > 0){
                        id = me.grid.uid();
                        me.grid.addRow(id, [resData[0],data.mun_codigo,data.mun_detalle,resData[1],data.mun_dpto]);
                        me.grid.selectRowById(id);
                        me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                        me.form.clear();
                        me.form.lock();
                        actionBar.enableItem('btn_new');
                    }
                    else
                        dhtmlx.alert({
                            text: response
                        });
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, ya existe el codigo '"+valCell.toUpperCase()+"', ingrese otro."
                });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    onClickButtonEditData: function(){
        var me = this,
            data,
            keyId,
            resData,
            rowId = (me.grid.getRowsNum() - 1);

        if(me.form.validate()){
            keyId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
            me.form.send(mainPath+'index.php/municipio/edit_data?id='+keyId, function(loader, response){
                resData = response.split('-');
                if(resData[0] == true){
                    data = me.form.getFormData();
                    me.grid.cellByIndex(rowId,2).setValue(data.mun_detalle);
                    me.grid.cellByIndex(rowId,3).setValue(resData[1]);
                    me.grid.cellByIndex(rowId,4).setValue(data.mun_dpto);
                    me.grid.groupBy(3);
                    me.grid.selectRowById(rowId + 1);
                    me.form.lock();
                    me.form.clear();
                    me.form.setItemFocus('btn_new');
                }
                else
                    dhtmlx.alert({
                        text: response
                    });
            });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    onEventActionToolBar: function(){
        var me = this;

        actionBar.attachEvent("onClick", function(itemId){
            switch(itemId){
                case 'btn_new':
                    me.onClickButtonNew(itemId);
                break;
                case 'btn_edit':
                    me.onClickButtonEdit();
                break;
                case 'btn_erase':
                    me.onClickButtonErase();
                break;
                case 'btn_clear':
                    me.onClickButtonClear();
                break;
            }
        });
    },
    onClickButtonNew: function(itemId){
        var me = this;

        actionBar.disableItem(itemId);
        me.form.clear();
        me.form.unlock();
        me.form.enableItem('mun_codigo');
        me.form.setItemFocus('mun_dpto');
        me.form.disableItem('edit_btn');
        me.form.enableItem('save_btn');
    },
    onClickButtonEdit: function(){
        var me = this,
            id = me.grid.getSelectedRowId();

        if(id != null){
            me.form.unlock();
            me.form.disableItem('save_btn');
            me.form.enableItem('edit_btn');
            me.form.setItemValue('mun_dpto', me.grid.cells(id,4).getValue());
            me.form.setItemValue('mun_codigo', me.grid.cells(id,1).getValue());
            me.form.setItemValue('mun_detalle', me.grid.cells(id,2).getValue());
            me.form.disableItem('mun_codigo');
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder editar."
            });
    },
    onClickButtonErase: function(){
        var me = this,
            rowId;

        if(me.grid.getSelectedRowId() != null){
            rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
            dhtmlx.confirm({
                text:"¿Esta seguro que quieres eliminar el Ítem?",
                callback: function(status){
                    if(status == true){
                        me.form.send(mainPath+'index.php/municipio/erase_data?id='+rowId, function(loader, response){
                            if(response != true)
                                dhtmlx.alert({
                                    text: response
                                });
                            else{
                                me.grid.deleteSelectedRows();
                                me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                            }
                        });
                    }
                }
            });
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder eliminar."
            });
    },
    onClickButtonClear: function(){
        var me = this;

        me.form.lock();
        me.form.clear();
        me.form.setItemFocus('btn_new');
        actionBar.enableItem('btn_new');
        me.grid.clearSelection();
    },
	widgetMain: function(){
        var me = muniClass;

		me.widgetWin();
		me.widgetGrid();
		me.widgetForm();
        me.onEventForm();
        me.onEventActionToolBar();
	}
};